<template>
  <el-dialog
    title="新建从机"
    width="350"
    v-model="visible"
    :show-close="false"
    :modal="true"
    :close-on-click-modal="false"
  >
    <el-form label-width="auto" @submit.native.prevent="addCommit">
      <el-form-item label="从机地址:" label-position="right">
        <el-input v-model.number="slaveId"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row class="custom-row">
        <el-form-item class="custom-form-item">
          <el-button type="primary" @click="addCommit">确定</el-button>
        </el-form-item>
        <el-form-item class="custom-form-item">
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-row>
    </template>
  </el-dialog>
</template>

<script setup name="AddSlave" lang="ts">
import { computed, ref } from "vue";
import { addSlave } from "@/api/slaveApi.ts";
import { ElMessage } from "element-plus";

let props = defineProps({
  deviceName: {
    type: String,
    required: true,
  },
  dialogVisible: {
    type: Boolean,
    required: true,
  },
  setDialogVisible: {
    type: Function,
    required: true,
  },
});
const visible = computed(() => props.dialogVisible);
const slaveId = ref<number | null>(null);
const emit = defineEmits(["addSuccess"]);

const addCommit = async () => {
  if (slaveId.value == null || slaveId.value < 0 || slaveId.value > 255) {
    ElMessage({
      type: "error",
      message: "从机地址不合法!",
      duration: 3000,
    });
    return;
  }
  const isSuccess = await addSlave(props.deviceName, slaveId.value);
  if (isSuccess) {
    props.setDialogVisible(false);
    emit("addSuccess", slaveId.value);
  }
};

const cancel = () => {
  props.setDialogVisible(false);
};
</script>

<style scoped>
.custom-row {
  display: flex;
  justify-content: center;
  /* 居中对齐 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
}

.custom-form-item {
  margin: 0 10px;
  /* 左右的间距，根据需要调整 */
}

/* 如果你不想给第一个和最后一个元素添加边距，可以使用伪类选择器 */
.custom-row .custom-form-item:first-child {
  margin-left: 0;
}

.custom-row .custom-form-item:last-child {
  margin-right: 0;
}
</style>
